package org.androidpush.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.androidpush.R;
import org.androidpush.greendao.Schedule;
import org.androidpush.greendao.ScheduleDao;
import org.androidpush.utils.ConstantUtils;
import org.androidpush.utils.DBUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huang on 2017/4/18 0018.
 */
public class ScheduleActivity extends Activity {

    private int itemHeight, marTop, marLeft;
    private String userId, requestWay;
    private LinearLayout[] weekPanels = new LinearLayout[7];
    private List<Schedule>[] scheduDatas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xml_schedule);
        ConstantUtils.aetActionBar(ScheduleActivity.this, getResources().getString(R.string.str_schedule));
        init();
        String url = ConstantUtils.URL + "JxhtWeb/CourseController/" + userId + "/getSchedule?requestWay=" + requestWay;
        Log.d("URL", url);
        new ScheduleAsyncTask().execute(url);
    }

    private void init() {
        SharedPreferences sp = ConstantUtils.getSharedPreferences(this);
        userId = sp.getString(ConstantUtils.USER_ID,"");
        requestWay = ConstantUtils.getStatusStrWithId(sp.getString(ConstantUtils.STATUS, ConstantUtils.STUDENT));
        itemHeight = getResources().getDimensionPixelSize(
                R.dimen.weekItemHeight);
        marTop = getResources().getDimensionPixelSize(R.dimen.weekItemMarTop);
        marLeft = getResources().getDimensionPixelSize(R.dimen.weekItemMarLeft);
    }

    public void addContentToWeekPanel(LinearLayout linearLayout, List<Schedule> data) {
        /*if (linearLayout == null || data == null || data.size() < 1)
            return;*/
        Schedule scheduFirst = data.get(0);
//        Log.d("Schedu", scheduFirst.toString());

        for (int i = 0; i < data.size(); i++) {
            Schedule schedule = data.get(i);
            TextView tv = new TextView(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, itemHeight
                    * (schedule.getTeaCouEnd() - schedule.getTeaCouStart() + 1) + marTop * (schedule.getTeaCouEnd() - schedule.getTeaCouStart()));
            if (i > 0) {
                lp.setMargins(marLeft,
                        (schedule.getTeaCouStart() - (scheduFirst.getTeaCouStart() + scheduFirst.getTeaCouEnd()))
                                * (itemHeight + marTop) + marTop, 0, 0);
            } else {
                lp.setMargins(marLeft, (schedule.getTeaCouStart() - 1)
                        * (itemHeight + marTop) + marTop, 0, 0);
            }

            tv.setLayoutParams(lp);
            tv.setTextColor(getResources().getColor(R.color.gray));
            tv.setGravity(Gravity.TOP);
            tv.setGravity(Gravity.CENTER_HORIZONTAL);
            tv.setTextSize(10);
            tv.setMaxLines(6);
            tv.setTextColor(getResources().getColor(R.color.schedulebule));
            tv.setText(schedule.getCouName() + "\n" + schedule.getTeaName() + "\n@" + schedule.getTeaCouAddress());
            int bgRes = ConstantUtils.getScheduleTextViewBG();
            tv.setBackgroundResource(bgRes);
            linearLayout.addView(tv);
            schedule = scheduFirst;
        }
    }

    public int sureCourseTime(String courseTime) {
        int i = -1;
        if ("周一".equals(courseTime) || "星期一".equals(courseTime))
            i = 0;
        else if ("周二".equals(courseTime) || "星期二".equals(courseTime))
            i = 1;
        else if ("周三".equals(courseTime) || "星期三".equals(courseTime))
            i = 2;
        else if ("周四".equals(courseTime) || "星期四".equals(courseTime))
            i = 3;
        else if ("周五".equals(courseTime) || "星期五".equals(courseTime))
            i = 4;
        else if ("周六".equals(courseTime) || "星期六".equals(courseTime))
            i = 5;
        else if ("周日".equals(courseTime) || "星期日".equals(courseTime))
            i = 6;
        return i;
    }

    public int initScheduDatas(List<Schedule> schedulist) {
        scheduDatas = new ArrayList[7];
        int max = 0;
        for (int i = 0; i < schedulist.size(); i++) {
            Schedule schedule = schedulist.get(i);
            int j = sureCourseTime(schedule.getTeaCouWeekTime());
            if(j>max){ max = j;}
            if (j >= 0) {
                if (scheduDatas[j] == null) {
                    scheduDatas[j] = new ArrayList<>();
                }
                scheduDatas[j].add(schedule);
            }
        }
        return max + 1;
    }

    class ScheduleAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return ConstantUtils.getDateFrom(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            ScheduleDao dao = DBUtils.getScheduleDao(ScheduleActivity.this);
            List<Schedule> resultlist = null;
//            Log.d("Result", result);
            if (ConstantUtils.STUDENT.equals(result)) {
                resultlist = dao.queryBuilder().list();
            } else {
                resultlist = ConstantUtils.parseJsonArrayWithGson(result, Schedule.class);
                Log.d("List",resultlist.toString());
                if (resultlist.size() > 0) {
                    dao.deleteAll();
                    for (Schedule schedu : resultlist) {
                        dao.insertOrReplace(schedu);
                    }
                }
            }

            int dateLines = initScheduDatas(resultlist);
            if (resultlist.size() > 0) {
                for (int i = 0; i < dateLines; i++) {
                    if (scheduDatas[i].size() > 0) {
                        weekPanels[i] = (LinearLayout) findViewById(R.id.id_schedule_week1 + i);
                        if (scheduDatas[i].size() > 0) {
//                            Log.d("scheduDatas" + i, scheduDatas[i].toString());
                            addContentToWeekPanel(weekPanels[i], scheduDatas[i]);
                        }
                    }
                }
            }
            DBUtils.closeDB();
        }
    }
}
